import threading
import pymysql
import hashlib
from pymysql.cursors import DictCursor
import random

from gglib import utils, logger
from gglib.settings import DATABASE
from gglib.user import User

_id_db_conns = {}


# 创建数据库连接为每一个线程
def _get_connection():
    t_id = threading.current_thread().ident
    if t_id not in _id_db_conns:
        print(DATABASE)
        db_options = DATABASE['OPTIONS']
        _id_db_conns[t_id] = pymysql.connect(user=db_options['USER'],
                                             password=db_options['PASSWORD'],
                                             host=db_options['HOST'],
                                             port=db_options.get("PORT", 3306),
                                             database=db_options['DB'],
                                             cursorclass=DictCursor,
                                             autocommit=True)

    return _id_db_conns[t_id]


# 将字典转化成逗号分割的字符串
def _dict_2_str(**kwargs):
    conds = []
    for key, value in kwargs.items():
        if isinstance(value, str):
            conds.append("{}='{}'".format(key, value))
        else:
            conds.append("{}={}".format(key, value))
    return " and ".join(conds)


def get_user(**kwargs):
    """
    select * from user where username='' and id=34
    :param kwargs:
    :return:
    """
    cursor = _get_connection().cursor()
    assert isinstance(cursor, DictCursor)
    try:
        sql = "select * from user where " + _dict_2_str(**kwargs)
        logger.debug("db", sql)
        result = cursor.execute(sql)
        if not result:
            return None
        return cursor.fetchone()
    finally:
        cursor.close()


def add_user(username, password, nickname=None):
    salt_value = utils.get_random_str(k=50)
    new_pwd = "{}:{}".format(password, salt_value)
    new_pwd = hashlib.md5(new_pwd.encode("utf-8")).hexdigest()
    cursor = _get_connection().cursor()
    try:
        sql = """insert into user (`username`, `password`, `salt`, `nickname`) value('{}', '{}', '{}', '{}')""".format(
            username, new_pwd, salt_value, nickname or '')
        logger.debug("add_user", sql)
        data = cursor.execute(sql)
        return data
    finally:
        cursor.close()
